<?php
require_once('db_connection.php');
try
{

  //Getting records (listAction)
  if($_GET["action"] == "list")
  {
    //Get record count
    $result = mysql_query("SELECT COUNT(*) AS RecordCount FROM users");
    $row = mysql_fetch_array($result);
    $recordCount = $row['RecordCount'];
    $sort = isset($_GET['jtSorting'])?$_GET['jtSorting']:'id DESC';
    //Get records from database
    $result = mysql_query("SELECT * FROM users ORDER BY $sort LIMIT " . $_GET["jtStartIndex"] . "," . $_GET["jtPageSize"] . ";");

    //Add all records to an array
    $rows = array();
    while($row = mysql_fetch_array($result))
    {
        $rows[] = $row;
    }

    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $jTableResult['TotalRecordCount'] = $recordCount;
    $jTableResult['Records'] = $rows;
    print json_encode($jTableResult);
  }
  //Creating a new record (createAction)
  else if($_GET["action"] == "create")
  {
   $_POST['added_date'] = date('Y-m-d H:i:s');
   $id = insert('users',$_POST);
   $row = fetchById('users',$id);

    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    $jTableResult['Record'] = $row;
    print json_encode($jTableResult);
  }
  //Updating a record (updateAction)
  else if($_GET["action"] == "update")
  {

    update('users',$_POST,"id=$_POST[id]");

    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    print json_encode($jTableResult);
  }
  //Deleting a record (deleteAction)
  else if($_GET["action"] == "delete")
  {
    //Delete from database

    deleteById('users',$_POST['id']);

    //Return result to jTable
    $jTableResult = array();
    $jTableResult['Result'] = "OK";
    print json_encode($jTableResult);
  }


}
catch(Exception $ex)
{
    //Return error message
  $jTableResult = array();
  $jTableResult['Result'] = "ERROR";
  $jTableResult['Message'] = $ex->getMessage();
  print json_encode($jTableResult);
}

?>
